package com.esteel

import android.app.Activity
import android.util.Log
import kotlinx.coroutines.*

/**
 * Created by Android Studio.
 * User: 赵宏图
 * Date: 2019/8/21
 * Time: 10:48
 * Email:zhaohongtu@payworth.cn
 * Desc:
 */

fun <T> Activity.executeRequest(request: suspend () -> T?, onSuccess: (T) -> Unit = {}, onFail: (Throwable) -> Unit = {}): Job {
    val uiScope = CoroutineScope(Dispatchers.Main)  // UI主线程的CoroutineScope
    return uiScope.launch {
        try {
            val res: T? = withContext(Dispatchers.IO) { request() }  // IO线程中执行网络请求，成功后返回这里继续执行
            res?.let {
                onSuccess(it)
            }
        } catch (e: CancellationException) {
            Log.e("executeRequest", "job cancelled")
        } catch (e: Exception) {
            Log.e("executeRequest", "request caused exception")
            onFail(e)
        }
    }
}
